package com.mall.user.services;/**
 * Created by ciggar on 2019/7/30.
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.user.IMemberService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.MemberConverter;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dto.*;
import com.mall.user.utils.AESUtil;
import com.mall.user.utils.ExceptionProcessorUtils;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  ciggar
 * create-date: 2019/7/30-下午11:51
 */
@Slf4j
@Component
@Service
public class MemberServiceImpl implements IMemberService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    RedissonClient redissonClient;

//    @Autowired
//    IUserLoginService userLoginService;

    @Autowired
    MemberConverter memberConverter;

    /**
     * 根据用户id查询用户会员信息
     * @param request
     * @return
     */
    @Override
    public QueryMemberResponse queryMemberById(QueryMemberRequest request) {
        QueryMemberResponse queryMemberResponse=new QueryMemberResponse();
        try{
            request.requestCheck();
            Member member=memberMapper.selectByPrimaryKey(request.getUserId());
            if(member==null){
                queryMemberResponse.setCode(SysRetCodeConstants.DATA_NOT_EXIST.getCode());
                queryMemberResponse.setMsg(SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
            }
            queryMemberResponse=memberConverter.member2Res(member);
            queryMemberResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            queryMemberResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("MemberServiceImpl.queryMemberById Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(queryMemberResponse,e);
        }
        return queryMemberResponse;
    }

    @Override
    public HeadImageResponse updateHeadImage(HeadImageRequest request) {
        HeadImageResponse response=new HeadImageResponse();
        //TODO
        return response;
    }

    @Override
    public UpdateMemberResponse updateMember(UpdateMemberRequest request) {
        return null;
    }

    @Override
    public UserLoginResponse verifyLogin(UserLoginRequest user) {
        AESUtil aesUtil = new AESUtil(user.getUserPwd());
        String password = aesUtil.encrypt().toLowerCase();
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", user.getUserName())
                .andEqualTo("password", password);
        List<Member> members = memberMapper.selectByExample(example);
        UserLoginResponse userLoginResponse = new UserLoginResponse();
        if (members.size() == 0) {
            userLoginResponse.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
            return userLoginResponse;
        }

        if ("N".equals(members.get(0).getIsVerified())) {
            userLoginResponse.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
            return userLoginResponse;
        }

        Map map = new HashMap<>();
        map.put("uid", members.get(0).getId());
        map.put("username", members.get(0).getUsername());
        map.put("file", members.get(0).getFile());

        JwtTokenUtils jwtTokenUtils = JwtTokenUtils.builder().msg(JSON.toJSONString(map)).build();
        String s = jwtTokenUtils.creatJwtToken();
        userLoginResponse.setId(members.get(0).getId());
        userLoginResponse.setUsername(members.get(0).getUsername());
        userLoginResponse.setState(members.get(0).getState());
        userLoginResponse.setToken(s);
        userLoginResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        userLoginResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        String str = JwtTokenUtils.builder().token(s).build().freeJwt();
        System.out.println(str);
        return userLoginResponse;
    }

    @Override
    public Map verify(String userInfo) {
        JSONObject obj = JSON.parseObject(userInfo);
        Map map = new HashMap();
        map.put("uid", obj.get("uid").toString());
        map.put("username", obj.get("username").toString());
        if (obj.size() == 2) {
            map.put("file", null);
        } else {
            map.put("file", obj.get("file").toString());
        }

        return map;
    }


//    @Override
//    public UpdateMemberResponse updateMember(UpdateMemberRequest request) {
//        UpdateMemberResponse response = new UpdateMemberResponse();
//        try{
//            request.requestCheck();
//            CheckAuthRequest checkAuthRequest = new CheckAuthRequest();
//            checkAuthRequest.setToken(request.getToken());
//            CheckAuthResponse authResponse = userLoginService.validToken(checkAuthRequest);
//            if (!authResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
//                response.setCode(authResponse.getCode());
//                response.setMsg(authResponse.getMsg());
//                return response;
//            }
//            Member member = memberConverter.updateReq2Member(request);
//            int row = memberMapper.updateByPrimaryKeySelective(member);
//            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
//            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
//            log.info("MemberServiceImpl.updateMember effect row :"+row);
//        }catch (Exception e){
//            log.error("MemberServiceImpl.updateMember Occur Exception :"+e);
//            ExceptionProcessorUtils.wrapperHandlerException(response,e);
//        }
//        return response;
//    }
}
